<template>
  <div>
    <ul>
      <li v-for="(item, index) in msgList" :key="index">
        用户：{{ item.user }} <br />
        信息：{{ item.msg }}<br />
        时间：{{ item.time }}
      </li>
    </ul>
    <input type="text" v-model.trim="msg" />
    <button @click="send">发送</button>
  </div>
</template>

<script>
import { favorite } from "../api/user/user";
// 创建websocket对象 websocket是window对象
// const ws = new WebSocket("ws:localhost:8000");
export default {
  data() {
    return {
      msg: "",
      msgList: [],
    };
  },
  async mounted() {
    const c = await favorite();
    console.log(c);
    const that = this;
    //websocket对象 绑定事件
    ws.addEventListener("open", that.handlOpen, false);
    ws.addEventListener("close", that.handlClose, false);
    ws.addEventListener("error", that.handlError, false);
    ws.addEventListener("message", that.handlMsg, false);
  },
  methods: {
    // 发送信息
    async send() {
      // if (this.msg) {
      //   ws.send(
      //     JSON.stringify({
      //       user: window.sessionStorage.getItem("user"),
      //       msg: this.msg,
      //       id: new Date().getTime(),
      //       time: new Date(),
      //     })
      //   );
      // }
    },
    // 连接服务
    handlOpen(e) {
      console.log("open", e);
    },
    // 关闭服务
    handlClose(e) {
      console.log("close", e);
    },
    //连接错误
    handlError(e) {
      console.log("error", e);
    },
    // 信息事件
    handlMsg(e) {
      //   console.log("msg", e.data);
      this.msgList.push(JSON.parse(e.data));
    },
  },
};
</script>